package cn.kgc.service.impl;

import cn.kgc.base.entity.LoginUserInfo;
import cn.kgc.commons.util.MD5Util;
import cn.kgc.constant.AuthorityCenterConstant;
import cn.kgc.entity.UmsMember;
import cn.kgc.mapper.UmsMemberMapper;
import cn.kgc.service.JwtService;
import cn.kgc.util.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;

/**
 * <p></p>
 *
 * @author 李孟鸠
 * @Date: 2022年12月02日8:53
 */
@Service("jwtService")
public class JwtServiceImpl  implements JwtService {

    @Resource
    private UmsMemberMapper umsMemberMapper;

    @Override
    public String token(String username, String password)throws Exception {
        return token(username,password, AuthorityCenterConstant.TOKEN_EXPIRE_TIME);
    }

    @Override
    public String token(String username, String password, int expire) throws Exception {
        LambdaQueryWrapper<UmsMember> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UmsMember::getUsername,username);
        password=MD5Util.md5(password);
        lambdaQueryWrapper.eq(UmsMember::getPassword,password);

        //查询用户
        UmsMember umsMember = umsMemberMapper.selectOne(lambdaQueryWrapper);
        if(umsMember==null){
            return null;
        }
        //产生令牌
        //令牌对应的用户信息
        LoginUserInfo loginUserInfo=new LoginUserInfo();
        BeanUtils.copyProperties(umsMember,loginUserInfo);
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH,expire);
        Date date = calendar.getTime();

        return JwtUtil.generateToken(loginUserInfo,date);
    }

    //注册并且生成令牌
    @Override
    public String register(String username, String password) throws Exception{
        UmsMember umsMember=new UmsMember();
        umsMember.setUsername(username);
        password=MD5Util.md5(password);  //密码加密以后保存
        umsMember.setPassword(password);

        umsMemberMapper.insert(umsMember);

        //生成令牌的用户对象
        LoginUserInfo loginUserInfo=new LoginUserInfo();
        BeanUtils.copyProperties(umsMember,loginUserInfo);

        //令牌的过期时间
        Calendar calendar= Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH,AuthorityCenterConstant.TOKEN_EXPIRE_TIME);
        Date date= calendar.getTime();
        return JwtUtil.generateToken(loginUserInfo,date);
    }
}
